//
//  PBOrderHomeController.m
//  PBHomeDemo
//
//  Created by Playboy on 2018/1/12.
//  Copyright © 2018年 tmkj. All rights reserved.
//

#import "PBOrderHomeController.h"
#import "PBOrderHomeTopCell.h"
#import "PBOrderNameCell.h"
#import "PBOrderMessageCell.h"
#import "PBOrderTimeCell.h"
#import "PBOrderSexCell.h"
#import "PBOrderSuccessController.h"

static NSString * const kPBOrderHomeTopCell = @"PBOrderHomeTopCell";
static NSString * const kPBOrderNameCell = @"PBOrderNameCell";
static NSString * const kPBOrderMessageCell = @"PBOrderMessageCell";
static NSString * const kPBOrderTimeCell = @"PBOrderTimeCell";
static NSString * const kPBOrderSexCell = @"PBOrderSexCell";

@interface PBOrderHomeController ()<UITableViewDelegate,UITableViewDataSource,PBOrderNameCellDelegate,PBOrderMessageCellDelegate,PBOrderSexCellDelegate,PBOrderTimeCellDelegate>
@property (strong, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSString       *name;
@property (nonatomic, strong) NSString       *phone;
@property (nonatomic, strong) NSString       *message;
@property (nonatomic, assign) NSInteger      sex;
@property (nonatomic, strong) NSString       *selectDate;
// 1全天 2上午 3下午 4晚上
@property (nonatomic, strong) NSString       *time;

@end

@implementation PBOrderHomeController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self configure];
}
- (void)configure {
    [self configureView];
    [self configureData];
}

- (void)configureView {
    [self.tableView registerNib:[UINib nibWithNibName:kPBOrderHomeTopCell bundle:nil] forCellReuseIdentifier:kPBOrderHomeTopCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBOrderNameCell bundle:nil] forCellReuseIdentifier:kPBOrderNameCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBOrderMessageCell bundle:nil] forCellReuseIdentifier:kPBOrderMessageCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBOrderTimeCell bundle:nil] forCellReuseIdentifier:kPBOrderTimeCell];
    [self.tableView registerNib:[UINib nibWithNibName:kPBOrderSexCell bundle:nil] forCellReuseIdentifier:kPBOrderSexCell];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tableViewTapMethod)];
    [self.tableView addGestureRecognizer:tap];
}
- (void)configureData {
    
}

- (void)tableViewTapMethod {
    [self.view endEditing:YES];
}

#pragma mark - <UITableViewDelegate,UITableViewDataSource>
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 3;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 1) {
        return 4;
    }
    return 1;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        PBOrderHomeTopCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBOrderHomeTopCell forIndexPath:indexPath];
        [cell refreshWithModel:self.model];
        return cell;
    }else if (indexPath.section == 1) {
        if (indexPath.row < 2) {
            PBOrderNameCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBOrderNameCell forIndexPath:indexPath];
            cell.delegate = self;
            [cell refreshWithIndexPath:indexPath];
            return cell;
        }else if (indexPath.row == 2) {
            PBOrderSexCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBOrderSexCell forIndexPath:indexPath];
            cell.delegate = self;
            return cell;
        }
        PBOrderTimeCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBOrderTimeCell forIndexPath:indexPath];
        cell.delegate = self;
        if (self.selectDate.length == 0) {
            [cell refreshWithString:@"请选择时间"];
        }else {
            [cell refreshWithString:[NSString stringWithFormat:@"%@ %@",self.selectDate,self.time]];
        }
        
        return cell;
    }else {
        PBOrderMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:kPBOrderMessageCell forIndexPath:indexPath];
        cell.delegate = self;
        return cell;
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        return 120;
    }else if (indexPath.section == 1) {
        return 50;
    }
    return 140;
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return 0.01f;
    }
    return 40;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 10;
}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section > 0) {
        UIView *header = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
        UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, kScreenWidth-15, 20)];
        label.font = [UIFont systemFontOfSize:12];
        label.textColor = [UIColor tm_secFontColor];
        [header addSubview:label];
        if (section == 1) {
            label.text = @"请填写下列信息，我们将尽快与您取得联系";
        }else if (section == 2) {
            label.text = @"给管家留言";
        }
        return header;
    }
    return nil;
}

#pragma mark - PBOrderNameCellDelegate
- (void)inputWithValue:(NSString *)value tag:(NSInteger)tag {
    if (tag == 100) {
        self.name = value;
    }else if (tag == 101){
        self.phone = value;
    }
    NSLog(@"%@ %@",self.name,self.phone);
}

#pragma mark - PBOrderMessageCellDelegate
- (void)backWithMessage:(NSString *)message {
    NSLog(@"%@",message);
    self.message = message;
}

#pragma mark - PBOrderSexCellDelegate
- (void)backWithSexType:(NSInteger)sex {
    if (sex == 0) {
        self.sex = 2;
    }else if (sex == 1) {
        self.sex = 1;
    }
}

#pragma mark - PBOrderTimeCellDelegate
- (void)backWithDate:(NSString *)date time:(NSString *)time {
    NSLog(@"date:%@",date);
    NSLog(@"time:%@",time);
    self.time = time;
    self.selectDate = date;
    [self.tableView reloadData];
}

- (void)keyboard {
    [self.view endEditing:YES];
}


// 提交预约
- (IBAction)commitButtonClick:(UIButton *)sender {
    
    if (self.name.length == 0) {
        [self showHint:@"请输入姓名"];
        return;
    }
    if (self.phone.length == 0) {
        [self showHint:@"请输入手机号"];
        return;
    }
    if (self.sex == 0) {
        self.sex = 1;
    }

    if (self.selectDate.length == 0) {
        [self showHint:@"请选择预约时间"];
        return;
    }

    NSString *timeStr;
    NSString *selectDateStr;
    if ([self.time isEqualToString:@"全天"]) {
        timeStr = @"1";
    }else if ([self.time isEqualToString:@"上午"]) {
        timeStr = @"2";
    }else if ([self.time isEqualToString:@"下午"]) {
        timeStr = @"3";
    }else if ([self.time isEqualToString:@"晚上"]) {
        timeStr = @"4";
    }

    NSDate *date = [NSDate date];
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    if ([self.selectDate containsString:@"今天"]) {
        selectDateStr = [dateFormatter stringFromDate:date];
    }else if ([self.selectDate containsString:@"明天"]) {
        selectDateStr = [self GetTomorrowDay:date];
    }else if ([self.selectDate containsString:@"后天"]) {
        selectDateStr = [self GetTomorrowDay:[self dateFromString:[self GetTomorrowDay:date]]];
    }else {
        selectDateStr = [dateFormatter stringFromDate:[self dateFromString2:[self.selectDate substringToIndex:6]]];
    }

    NSDictionary *param = @{@"houseId":[NSString stringWithFormat:@"%zd",self.model.ID],
                            @"contacts":self.name,
                            @"contactTime":selectDateStr,
                            @"message":self.message?self.message:@"",
                            @"contactTimeOption":timeStr,
                            @"contactsSex":[NSString stringWithFormat:@"%zd",self.sex],
                            @"contactsMobile":self.phone};
    [TMNetwork requestPostWithParam:param url:@"/user/houseAppointment" callback:^(TMBaseReqModel *model) {
        if (model.code == 200) {
            PBOrderSuccessController *vc = [[PBOrderSuccessController alloc] init];
            [self.navigationController pushViewController:vc animated:YES];
        }else if (model.code == 401) {
            PBLoginViewController *loginVC = [[PBLoginViewController alloc] init];
            [self.navigationController pushViewController:loginVC animated:YES];
        }else {
            [self showHint:model.message];
        }
    }];

}

//将字符串转成NSDate类型
- (NSDate *)dateFromString:(NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"yyyy-MM-dd"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}

- (NSDate *)dateFromString2:(NSString *)dateString {
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat: @"MM月dd日"];
    NSDate *destDate= [dateFormatter dateFromString:dateString];
    return destDate;
}

//传入今天的时间，返回明天的时间
- (NSString *)GetTomorrowDay:(NSDate *)aDate {
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *components = [gregorian components:NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitMonth | NSCalendarUnitDay fromDate:aDate];
    [components setDay:([components day]+1)];
    
    NSDate *beginningOfWeek = [gregorian dateFromComponents:components];
    NSDateFormatter *dateday = [[NSDateFormatter alloc] init];
    [dateday setDateFormat:@"yyyy-MM-dd"];
    return [dateday stringFromDate:beginningOfWeek];
}

#pragma mark - super
- (void)resetNavigationBarItems {
    [super resetNavigationBarItems];
    self.title = @"预约看房";
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
